<template>
  <div style="height: 900px">
    <a-card class="chat-card">
      <div class="chat-window">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <strong>{{ message.sender }}:</strong>
          <pre class="language-html">
            <code><span v-html="formatMessage(message.text)"></span></code>
          </pre>
        </div>
      </div>
      <div style="display: flex; width: 50%;margin: 0 auto">
        <a-textarea
          v-model="userInput"
          @pressEnter="sendMessage"
          placeholder="请输入问题"
        />
        <a-button type="primary" @click="sendMessage" :loading="loading" style="margin-top: 10px ">
          发送
        </a-button>
      </div>
    </a-card>
  </div>
</template>

<script>
import { chat } from '@/api/chat'

export default {
  data() {
    return {
      userInput: '',
      messages: [],
      loading: false,
      sessionId: null,
      userId: this.$store.getters.userInfo.uid,
      userName: this.$store.getters.userInfo.name,

    };
  },

  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') return;
      const userMessage = this.userInput.trim();
      const userQuestion = { sender: '用户', text: userMessage }; // 保存用户问题
      this.messages.push(userQuestion); // 推送用户问题到 messages 数组
      this.userInput = '';
      this.loading = true;
      const parameter = {
        sessionId: this.sessionId,
        question: userMessage,
        userId: this.userId,
        userName: this.userName
      };
      console.log(parameter)
      const res = await chat(parameter)
      this.sessionId = res.data.sessionId;
      try {
        const eventSource = new EventSource(`http://localhost:8080/fastChat/sse/dashScope/`+this.sessionId);
        eventSource.onmessage = (event) => {
          let data = event.data;
          console.log(data);
          if (this.messages[this.messages.length - 1].sender === "用户") {
            let text = this.formatMessage(data);
            text = this.autoInsertLineBreak(text); // 在两个换行符之间的汉字超过45时，自动插入一个换行符
            this.messages.push({ sender: '小助手', text: text });
          } else {
            let text = this.formatMessage(data);
           /* text = this.autoInsertLineBreak(text);*/
            this.messages[this.messages.length - 1].text = text;
          }
          this.loading = false;
        };

        eventSource.onerror = (error) => {
          console.error("EventSource error:", error);  // 输出错误日志
          if (error.eventPhase === EventSource.CLOSED) { // 仅在连接已经关闭的情况下调用
            eventSource.close();
          }
        };

      } catch (error) {
        const errorMessage = { sender: '系统', text: '发送失败，请稍后再试。' }; // 保存错误消息
        this.messages.push(errorMessage); // 推送错误消息到 messages 数组
        this.loading = false;
      }
    },
    formatMessage(text) {
      // 将换行符替换为 <br> 标签
      // 将 \sb 替换为 <br>
      text = text.replace(/\\sb/g, '<br><br>');
      text = text.replace(/\*\*(.*?)\*\*/g, '<span class="highlight">$1</span>');
      return text;
    },
    autoInsertLineBreak(text) {
      const lines = text.split('<br><br>'); // 按两个换行符分割文本
      console.log(lines);
      const maxLength = 200; // 限制每行的最大字符数
      const resultLines = [];
      for (let line of lines) {
        let newLine = '';
        let count = 0;
        for (let char of line) {
          newLine += char;
          count++;
          if (count >= maxLength && char.match(/[\u4e00-\u9fa5]/)) { // 汉字计数
            newLine += '<br>'; // 插入换行符
            count = 0; // 重置计数器
          }
        }
        resultLines.push(newLine);
      }
      return resultLines.join('<br><br>'); // 重新组合文本
    },

  }
};
</script>

<style>
.chat-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止卡片本身出现滚动条 */
}

.chat-window {
  height: 500px;
  flex-grow: 1;
  overflow-y: auto;
  overflow-x: hidden; /* 防止横向滚动条 */
  margin-bottom: 20px;
  border: 1px solid #f0f0f0;
  padding: 10px;
  background: #fafafa;
  white-space: pre-line; /* 允许换行 */
}

.chat-window::-webkit-scrollbar {
  width: 10px; /* 滚动条宽度 */
}

.chat-window::-webkit-scrollbar-thumb {
  background-color: #888; /* 滚动条颜色 */
  border-radius: 10px; /* 滚动条圆角 */
}

.chat-window::-webkit-scrollbar-thumb:hover {
  background-color: #555; /* 滚动条悬停颜色 */
}

.chat-window::-webkit-scrollbar-track {
  background-color: #f0f0f0; /* 滚动条轨道颜色 */
}

.message {
  margin-bottom: 10px;
  word-wrap: break-word; /* 防止长单词导致横向滚动条 */
}

.code-block {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
}

.highlight {
  font-weight: bold;
  font-size: 1.5em; /* 或者你希望的其他样式 */
}
</style>